let obj = {
    // baseUrl: 'http://api-breakingnews-web.itheima.net',
    upLoadFile: false,
    baseUrl: 'http://www.liulongbin.top:3007',
    requestHeaders: localStorage.getItem('mima') || ''
}
let hij = document.getElementsByTagName("body")[0]
let progress = document.createElement('div')
progress.id = 'progress'
progress.style.cssText = 'position:absolute;height: 30px;top:442px;left: 111px;z-index: 999;display: block;text-align: center;display:none;width:0;line-height: 30px;font-size: 20px;background-color: blue;color: white;'
hij.insertBefore(progress, hij.children[0])
function myAxios(obj) {
    let xhr = new XMLHttpRequest()
    // let progress = document.querySelector('#progress')
    progress.style.display = 'block'
    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            let str = Math.ceil(100 * e.loaded / e.total)
            progress.style.width = str * 2 + 'px'
            progress.innerHTML = str + '%'
        }
    }
    let str = obj.data && objToString(obj.data)
    if (obj.type.toUpperCase() === 'GET') {
        let urlStr = obj.data ? obj.url + '?' + str : obj.url
        xhr.open('get', obj.baseUrl ? obj.baseUrl + urlStr : urlStr)
        obj.requestHeaders && xhr.setRequestHeader('Authorization', obj.requestHeaders)
        xhr.send()
    } else if (obj.type.toUpperCase() == 'POST') {
        xhr.open('post', obj.baseUrl ? obj.baseUrl + obj.url : obj.url)
        //当上传文件时不发送这个请求头
        if (obj.upLoadFile) {
            obj.requestHeaders && xhr.setRequestHeader('Authorization', obj.requestHeaders)
            xhr.send(obj.data)
        }
        else {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            obj.requestHeaders && xhr.setRequestHeader('Authorization', obj.requestHeaders)
            xhr.send(str)
        }
    }
    xhr.onreadystatechange = function () {
        progress.style.display = "none"
        if (xhr.readyState === 4 && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText)
            if (data.status === 1 && data.message === '身份认证失败！') {
                localStorage.removeItem('mima')
                window.location.assign('/login.html')
            }
            else {
                obj.success(data)
            }
        }
    }
}
function objToString(obj) {
    let arr = []
    for (const key in obj) {
        arr.push(key + '=' + obj[key])
    }
    return arr.join('&')
}